package Contest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import Access_check.Access_checkMapper;
import Attachment.AttachmentMapper;
import Board.BoardItem;
import Board.BoardMapper;
import Content.ContentItem;
import Content.ContentMapper;
import Content_check.Content_checkMapper;
import Contest_reg.Contest_regMapper;
import Contest_reg_file.Contest_reg_fileItem;
import Contest_reg_file.Contest_reg_fileMapper;
import Member.MemberItem;
import Member.MemberMapper;
import Proposal.ProposalItem;
import Proposal.ProposalMapper;
import Regdate.RegdataMapper;
import Reply.ReplyMapper;
import Schedule.ScheduleMapper;
import Subject.SubjectItem;
import Subject.SubjectMapper;
import Team.TeamItem;
import Team.TeamMapper;
import TeamSkill.TeamSkillMapper;
import Teamdata.TeamdataMapper;
import Track.TrackMapper;
import User.UserMapper;

@Controller
public class ContestController {
	@Autowired
	private ContentMapper contentMapper;
	
	@Autowired
	private SubjectMapper subjectMapper;
	
	@Autowired
	private ScheduleMapper scheduleMapper;
	
	@Autowired
	private ReplyMapper replyMapper;
	
	@Autowired
	private MemberMapper memberMapper;
	
	@Autowired
	private ContestMapper contestMapper;

	@Autowired
	private Contest_regMapper contest_regMapper;
	
	@Autowired
	private TrackMapper trackMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private TeamMapper teamMapper;
	
	@Autowired
	private ProposalMapper proposalMapper;
	
	@Autowired
	private BoardMapper boardMapper;
	
	@Autowired
	private Contest_reg_fileMapper contest_reg_fileMapper;
	
	@Autowired
	private Content_checkMapper content_checkMapper;
	
	@Autowired
	private Access_checkMapper access_checkMapper;
	
	@Autowired
	private TeamSkillMapper teamSkillMapper;
	
	@Autowired
	private RegdataMapper regdataMapper;
	
	@Autowired
	private TeamdataMapper teamdataMapper;
	
	@RequestMapping("/common/contest_list.do")
	public @ResponseBody HashMap<String,Object> list(){
		HashMap<String, Object> list=new HashMap<String,Object>();
		list.put("e_finish", contest_regMapper.selectFinish());
		list.put("d_end", contest_regMapper.selectEnddate());
		
		list.put("a_ready", contest_regMapper.selectReady());
		list.put("b_apply", contest_regMapper.selectApplydate());
		list.put("c_report", contest_regMapper.selectIng());
		
        return list;
	}
	
	// 여기
	@RequestMapping("/common/contest_reg.do")
	public @ResponseBody HashMap<String,Object> contest_reg(int id){
		HashMap<String,Object> list = new HashMap<String,Object>();
		list.put("contest_reg",contest_regMapper.selectById(id)); // 대회정보
		list.put("track",trackMapper.selectByCon(id)); // 대회-회차의 주제들..
		list.put("contest_reg_file", contest_reg_fileMapper.selectByConId(id)); // 
		list.put("schedule", scheduleMapper.selectByCon(id)); // 대회-회차의 일정들..
		if(!(SecurityContextHolder.getContext().getAuthentication().getPrincipal().equals("anonymousUser"))){
			User user =(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			list.put("user",memberMapper.selectById(user.getUsername()));
			if(!userMapper.selectByIdRegId(user.getUsername(),id).isEmpty()){ // 로그인 대회참가 여부, 관리자도 false
				list.put("join",true);
			}
			else if(user.getAuthorities().equals("ROLE_ADMIN")){ // 관리자
				list.put("join", false);
				list.put("teamList", contest_regMapper.selectTeamById(id));
			}
			else
				list.put("join", false);
		}
		else{
			list.put("join", false); // 비회원
		}
			
		if(contest_regMapper.selectContestById(id).getFinish() == 1)
		{
			list.put("teamList", contest_regMapper.selectTeamById(id));
		}
		return list;
	}
	
	@RequestMapping("/common/teamChange.do")
	public @ResponseBody List<HashMap<String,Object>> teamChange(String str,String temp,int track_id,int contest_reg_id){
		return memberMapper.selectTeamMemberSearch(str, temp, track_id, contest_reg_id);
	}
	
	@RequestMapping("/common/teamNameCheck.do")
	public @ResponseBody HashMap<String,Object> teamNameCheck(int contest_reg_id,String teamName){
		HashMap<String,Object> message = new HashMap<String,Object>();
		
		
		if(teamMapper.selectByIdName(contest_reg_id, teamName)==null){
			message.put("check", true);
			message.put("color", "green");
			message.put("message", "�궗�슜媛��뒫�븳 ��紐낆엯�땲�떎.");
		}
		else{
			message.put("check", false);
			message.put("color", "red");
			message.put("message", "�궗�슜遺덇��뒫�븳 ��紐낆엯�땲�떎.");
		}
		return message;
	}
	
	@RequestMapping("/common/trackCheck.do")
	public @ResponseBody HashMap<String,Object> trackCheck(int track_id,int contest_reg_id,@RequestBody List<HashMap<String,Object>> students){
		boolean check=false;
		HashMap<String,Object> message= new HashMap<String,Object>();
		
		String track_check = contest_regMapper.selectById(contest_reg_id).get("track_check").toString();
	
		if(track_check.equals("true")){
			for( HashMap<String, Object> student : students){
				if(!memberMapper.selectUserIdTrack3(student.get("id").toString(),contest_reg_id,track_id).isEmpty()){
					check=true;
				}
			}
		}
		else{
			for( HashMap<String, Object> student : students){
				if(!memberMapper.selectUserIdContest_reg3(student.get("id").toString(),contest_reg_id).isEmpty()){
					check=true;
					
				}
			}
		}
		message.put("check", check);
		if(check){
			message.put("message", "�떊泥�媛��뒫�빀�땲�떎.");
			message.put("color", "green");
			
		}
		else{
			message.put("message", "李몄뿬 �븷 �닔 �뾾�뒗 �븰�깮�씠 議댁옱�빀�땲�떎.");
			message.put("color", "red");
		}
		return message;

	}
	
	@RequestMapping(value = "/common/apply.do", method = RequestMethod.POST)
    public ModelAndView post(@RequestParam("file") MultipartFile multipartFile,@RequestParam("contest_reg_id") int contest_reg_id,
    		@RequestParam("teamName") String teamName,@RequestParam("track_id") int track_id,@RequestParam("user") List<String> user,
    		@RequestParam("leader") String leader) throws IOException 
    {
		ModelAndView result = new ModelAndView("main");
		HashMap<String,Object> team = new HashMap<String,Object>();
		HashMap<String,Object> users = new HashMap<String,Object>();
		
		
		team.put("contest_reg_id", contest_reg_id);
		team.put("track_id",track_id);
		team.put("team_name", teamName);
		team.put("flag",0);

		
        if (multipartFile != null && multipartFile.isEmpty() == false) {
            ProposalItem fileModel = new ProposalItem();
            fileModel.setFileName(multipartFile.getOriginalFilename());
            fileModel.setFileSize((multipartFile.getSize()));
            fileModel.setData(multipartFile.getBytes());
            proposalMapper.insert(fileModel);
            
            team.put("proposal",fileModel.getFileId());
        }
        
        teamMapper.insert(team);
        
        users.put("team_id", team.get("team_id"));
        users.put("enable", 1);
        
        
        for(String item : user){
        	users.put("id", item);
			if(item.equals(leader))
				users.put("position","���옣");
			else
				users.put("position","���썝");
			userMapper.insert(users);
		}
        return result;
    }
	

	
	@RequestMapping("/common/contestAll.do")
	public @ResponseBody List<HashMap<String,Object>> contestAll(){
		return contestMapper.selectAll();
	}
	
	@RequestMapping("/common/countCheck.do")
	public @ResponseBody boolean countCheck(int contest_id,int count){
		return contest_regMapper.selectByConCount(contest_id, count)==null;
	}
	
	@RequestMapping("/common/contestNameCheck.do")
	public @ResponseBody boolean contestNameCheck(String name){
		return contestMapper.selectByName(name)==null;
	}
	
	@RequestMapping("/common/createContest.do")
	public ModelAndView createContest(@RequestParam(value="contest_id",required=false) Integer contest_id,@RequestParam(value="name" ,required=false) String name  ,@RequestParam("count") int count,
			@RequestParam("track_check") int track_check,
			@RequestParam("tracks") List<String> tracks,@RequestParam("contest_reg_date") List<String>  contest_reg_date ,
			@RequestParam(value="schedule_name",required=false) List<String> schedule_name,
			@RequestParam(value="schedule" ,required=false) List<String> schedule, @RequestParam("file") List<MultipartFile> files,
			@RequestParam("content") String content) throws IOException{
		
		HashMap<String,Object> contest=new HashMap<String,Object>();
		contest.put("name",name);
		
		ModelAndView result=new ModelAndView("main");
		if(contest_id==null){
			contestMapper.insert(contest);
		}else{
			contest.put("contest_id",contest_id);
		}
		
		HashMap<String,Object> contest_reg=new HashMap<String,Object>();
		contest_reg.put("apply_start_date",contest_reg_date.get(0));
		contest_reg.put("apply_end_date",contest_reg_date.get(1));
		contest_reg.put("report_start_date",contest_reg_date.get(2));
		contest_reg.put("report_end_date",contest_reg_date.get(3));
		contest_reg.put("enddate",contest_reg_date.get(4));
		contest_reg.put("content",content);
		contest_reg.put("count",count);
		contest_reg.put("track_check",track_check);
		contest_reg.put("finish",0);
		contest_reg.put("contest_id",contest.get("contest_id"));
		
		
		contest_regMapper.insert(contest_reg);
		
		if(tracks !=null && tracks.size()>0){
		
			HashMap<String,Object> track = new HashMap<String,Object>();
		
		
			for(String item : tracks){
				track.put("track_name", item);
				track.put("contest_reg_id", contest_reg.get("contest_reg_id"));
				trackMapper.insert(track);
			}
		}
		
		if (files != null && files.isEmpty() == false) {
			HashMap<String,Object> contest_reg_file =new HashMap<String,Object>();
			contest_reg_file.put("contest_reg_id", contest_reg.get("contest_reg_id"));
			for (MultipartFile multipartFile : files) {
				contest_reg_file.put("file_name",multipartFile.getOriginalFilename());
				contest_reg_file.put("file_size",multipartFile.getSize());
				contest_reg_file.put("data",multipartFile.getBytes());
				contest_reg_fileMapper.insert(contest_reg_file);
			}
        }
		
		if(schedule!=null && schedule.size()>0){
		
			HashMap<String,Object> schedule_date = new HashMap<String,Object>();
			schedule_date.put("contest_reg_id", contest_reg.get("contest_reg_id"));
		
			for(int i=0;i<schedule.size();i++){
				schedule_date.put("schedule_name",schedule_name.get(i));
				schedule_date.put("schedule_date",schedule.get(i));
				scheduleMapper.insert(schedule_date);
			}
		}
		
		HashMap<String,Object> board = new HashMap<String,Object>();
		
		
		board.put("contest_reg_id", contest_reg.get("contest_reg_id"));
		
		if(contest_id==null){
			board.put("board_name", contestMapper.selectById(Integer.parseInt(contest.get("contest_id").toString())).getName() + count+"�쉶李� 寃뚯떆�뙋");
		}
		else{
			board.put("board_name", contestMapper.selectById(contest_id).getName()+count+"�쉶李� 寃뚯떆�뙋");
		}
		board.put("contest_id", contest_reg.get("contest_reg_id"));
		boardMapper.insert(board);

		return result;
	}
	
	@RequestMapping("/common/contest_reg_applyDate.do")
	public @ResponseBody HashMap<String,Object> contest_reg_applyDate(){
		HashMap<String,Object> list = new HashMap<String,Object>();
		list.put("contest_reg",contest_regMapper.selectApplydate());
		list.put("team",teamMapper.selectAllFlag0());
		return list;
	}
	
	@RequestMapping("/common/userList.do")
	public @ResponseBody List<HashMap<String,Object>> userList(int team_id){
		return userMapper.selectByTeamId(team_id);
	}
	
	@RequestMapping("/common/accessYes.do")
	public @ResponseBody void accessYes(@RequestBody HashMap<String,Object> team){

		int team_id=Integer.parseInt(team.get("team_id").toString());
		
		teamMapper.updateFlag(team_id);
		
		
		HashMap<String,Object> board =new HashMap<String,Object>();
		board.put("board_name",team.get("team_name")+"寃뚯떆�뙋");
		board.put("team_id",team.get("team_id"));
		boardMapper.insert2(board);

		
		
		HashMap<String,Object> content_check=new HashMap<String,Object>();
		
		HashMap<String,Object> user=new HashMap<String,Object>();
		
		user=userMapper.selectByTeamLeader(team_id);
		
		access_checkMapper.update(user.get("id").toString(), team_id,1); //�듅�씤
		
		for(HashMap<String,Object> item : userMapper.selectByTeamId(team_id)){
			for(ContentItem con : contentMapper.selectByBoard_id(boardMapper.selectContest_id(teamMapper.selectById(team_id).getContest_reg_id()).getBoard_id())){
				content_check.put("content_id", con.getContent_id());
				content_check.put("id", user.get("id"));

				if(content_checkMapper.selectId(user.get("id").toString(), con.getContent_id()).isEmpty()){
					content_checkMapper.insert(content_check);
				}
			}
		}
		
		
	}
	
	@RequestMapping("/common/accessNo.do")
	public @ResponseBody void accessNo(int team_id){
		HashMap<String,Object> user = userMapper.selectByTeamLeader(team_id);
		
		access_checkMapper.update(user.get("id").toString(), team_id, 2);
		access_checkMapper.updateTeam_id(user.get("id").toString(), team_id);
		
		teamMapper.delete(team_id);
		
	}
	
	@RequestMapping("/common/proposalDownload.do")
	public String proposalDownload(int id,HttpServletRequest request){
		ProposalItem fileModel = proposalMapper.selectById(id);
		request.setAttribute("fileModel",fileModel);
		return "forward:/ProposalDownloadServlet";
	}
	
	@RequestMapping("/common/contest_reg_fileDownload.do")
    public String contest_reg_filedownload(int id, HttpServletRequest request) {
		Contest_reg_fileItem fileModel= contest_reg_fileMapper.selectByFileId(id);
        request.setAttribute("fileModel", fileModel);
        return "forward:/Contest_reg_fileDownloadServlet";
        
    }
	
	@RequestMapping("/common/contest_reg2.do")
	public @ResponseBody List<HashMap<String,Object>> contest_reg2(int id){

		return contest_regMapper.selectByContestId(id);
	}
	
	@RequestMapping("/common/teamSearch.do")
	public @ResponseBody List<HashMap<String,Object>> teamSearch(int contest_reg_id){
		return teamMapper.selectByCon_reg2(contest_reg_id);
	}
	
	@RequestMapping("/common/teamList.do")
	public @ResponseBody List<HashMap<String,Object>> teamList(int contest_reg_id){
		
		List<HashMap<String,Object>> teamList=new ArrayList<HashMap<String,Object>>();
		
		for(HashMap<String,Object> item: teamMapper.selectByCon_reg4(contest_reg_id)){
			int team_id=Integer.parseInt(item.get("team_id").toString());
			item.put("team", teamMapper.selectById2(team_id));
			item.put("user", userMapper.selectByTeamId2(team_id));
			item.put("count", userMapper.userCount(team_id));
			item.put("leader", userMapper.selectByTeamLeader(team_id));
			teamList.add(item);
		}
		
		return teamList;
	}
	@RequestMapping("/common/reportList.do")
	public @ResponseBody List<HashMap<String,Object>> reportList(int contest_reg_id){
		return regdataMapper.selectReg(contest_reg_id);
	}
	
	@RequestMapping("/common/reportComplete.do")
	public @ResponseBody HashMap<String,Object> reportComplete(String regdata_name,int regdata_id,int contest_reg_id){
		
		if(regdataMapper.selectByName(regdata_name,contest_reg_id)==null){
			HashMap<String,Object> regdata=new HashMap<String,Object>();
			regdata.put("regdata_id", regdata_id);
			regdata.put("regdata_name", regdata_name);
			regdataMapper.update(regdata);
			return regdataMapper.selectById(regdata_id);
		}
		else{
			return null;
		}
	}
	

	
	@RequestMapping("/common/reportDelete.do")
	public @ResponseBody boolean reportDelete(int regdata_id){
		
		if(teamdataMapper.selectByRegdataId(regdata_id).isEmpty()){
			regdataMapper.delete(regdata_id);
			return true;
		}
		else{
			return false;
		}
	}
	
	@RequestMapping("/common/contest_board.do")
	public @ResponseBody HashMap<String,Object>contest_board(int contest_reg_id){
		HashMap<String,Object> list = new HashMap<String,Object>();
		BoardItem board = boardMapper.selectContest_id(contest_reg_id);
		int board_id=board.getBoard_id();
		list.put("board",board);
		list.put("content", contentMapper.selectAll(null, null,board_id , null));
		return list;
	}
	
	@RequestMapping("/common/team_board.do")
	public @ResponseBody HashMap<String,Object>team_board(int team_id){
		HashMap<String,Object> list = new HashMap<String,Object>();
		BoardItem board = boardMapper.selectTeam_id(team_id);
		int board_id=board.getBoard_id();
		list.put("board",board);
		list.put("content", contentMapper.selectAll(null, null,board_id , null));
		return list;
	}
	
	@RequestMapping("/common/reportAdd.do")
	public @ResponseBody HashMap<String,Object> reportAdd(String regdata_name,int contest_reg_id){
		if(regdataMapper.selectByName(regdata_name, contest_reg_id)==null){
			HashMap<String,Object> regdata=new HashMap<String,Object>();
			regdata.put("regdata_name", regdata_name);
			regdata.put("contest_reg_id", contest_reg_id);
			regdataMapper.insert(regdata);
		
			return regdata;
		}
		return null;
	}
	
	@RequestMapping("common/myTeamList.do")
	public @ResponseBody List<TeamItem> myTeamList(String id,int contest_reg_id){
		return teamMapper.selectByIdReg(id, contest_reg_id);
	}

}
